import { createRouter, createWebHashHistory } from 'vue-router';

// 懒加载页面
const InventoryPlanManagement = () => import('../pages/warehousingEntry.vue');
const OutboundOrder = () => import('../pages/OutboundOrder.vue');
const Listing = () => import('../pages/Listing.vue');

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      name: 'inbound',
      component: InventoryPlanManagement
    },
    {
      path: '/outbound',
      name: 'outbound',
      component: OutboundOrder,
      props: route => ({
        receipts: (route.state && Array.isArray(route.state.receipts))
          ? route.state.receipts
          : ((window.history && window.history.state && Array.isArray(window.history.state.receipts)) ? window.history.state.receipts : [])
      })
    },
    {
      path: '/listing',
      name: 'listing',
      component: Listing,
      props: route => ({
        outbound: (route.state && route.state.receipt)
          ? route.state.receipt
          : (window.history && window.history.state ? window.history.state.receipt : null)
      })
    },
    // 兜底：未知路径重定向到入库计划单
    { path: '/:pathMatch(.*)*', redirect: { name: 'inbound' } }
  ]
});

// 守卫：缺参数时回退到上一级，确保初次进入为入库计划单
router.beforeEach((to, from, next) => {
  // 首次进入强制落在 inbound
  const isFirstLoad = !from.name && from.matched.length === 0;
  if (isFirstLoad && to.name !== 'inbound') {
    return next({ name: 'inbound' });
  }


  if (to.name === 'listing') {
    // 静态页面放行，不再强校验 state
  }
  return next();
});

export default router; 